import 'dart:convert';
import 'dart:ui';
import 'package:basic/common/api.dart';
import 'package:basic/common/data.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Market extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(alignment: Alignment.center, child: MyMarket()));
  }
}

List mylist = [];
MyGoods list = MyGoods(data: mylist);
_postParam(int type) async {
  //Paramr
  var url = Uri.parse(Api.url + '/market/get');
  var response = await http.post(url);
  mylist = jsonDecode(response.body);
  print('收到的数据...');
  print(mylist);
  list.fresh();
}

var scrollController = new ScrollController();

class MyMarket extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // _postParam();
    return Scaffold(
        appBar: PreferredSize(
          child: AppBar(
            flexibleSpace: SearchBarWidget(), //设置搜索栏
            backgroundColor: Colors.white,
            elevation: 0, //将向导栏的阴影设为0，确保全透明
            title: Text(
              "积分商城",
              style: TextStyle(fontSize: 20.0, color: Colors.black),
            ),
            centerTitle: true,
            leading: IconButton(
              icon: Icon(Icons.chevron_left),
              color: Colors.grey,
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            bottom: PreferredSize(
              preferredSize: const Size.fromHeight(10.0),
              child: Row(
                children: [
                  TextButton(
                    child: Text("最新"),
                    onPressed: () {
                      _postParam(1);
                    },
                  ),
                  TextButton(
                    child: Text("销量"),
                    onPressed: () {
                      _postParam(2);
                    },
                  ),
                  TextButton(
                    child: Text("价格"),
                    onPressed: () {
                      _postParam(3);
                    },
                  )
                ],
              ),
            ),
          ),
          preferredSize: Size.fromHeight(120.0),
        ),
        floatingActionButton: Container(
          //设置悬浮一键恢复顶部按钮
          child: FloatingActionButton(
            shape: CircleBorder(side: BorderSide(color: Colors.red[300])),
            child: Icon(
              Icons.publish,
              color: Colors.red[50],
              size: 45,
            ),
            onPressed: () {
              scrollController.jumpTo(0.0);
            },
            backgroundColor: Color.fromARGB(450, 250, 100, 100),
            elevation: 0,
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
        body: Container(child: list)
        //防止页面溢出
        );
  }
}

//单个商品的组件
class Agood extends StatelessWidget {
  final String title;
  final String imageUrl;
  final int score;
  final int number;

  Agood(this.title, this.imageUrl, this.score, this.number); //构造函数定义

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
        child: InkWell(
          //设置为能够点击
          onTap: () {},
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                //设置图片与文字的水平分布为1:2
                flex: 1,
                child: Image.asset(
                  //设置图片
                  imageUrl,
                  fit: BoxFit.cover,
                ),
              ),
              SizedBox(width: 10),
              Expanded(
                  flex: 2,
                  child: Column(children: [
                    //设置文字部分，包括标题、内容和按钮
                    Text(
                      title,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                      style: TextStyle(
                        fontSize: 20.0,
                      ),
                    ),
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                score.toString() + "积分",
                                style:
                                    TextStyle(fontSize: 20, color: Colors.red),
                              ),
                              SizedBox(height: 5),
                              Text(
                                number.toString() + "销量",
                                style:
                                    TextStyle(fontSize: 15, color: Colors.grey),
                              ),
                            ],
                          ),
                          SizedBox(width: 5.0),
                          ElevatedButton(
                            //设置按钮
                            child: Text("加购物车"),
                            style: ButtonStyle(
                              backgroundColor:
                                  MaterialStateProperty.all(Colors.red),
                              foregroundColor:
                                  MaterialStateProperty.all(Colors.white),
                              elevation: MaterialStateProperty.all(0),
                              shape: MaterialStateProperty.all(StadiumBorder()),
                            ),
                            onPressed: () {},
                          )
                        ])
                  ]))
            ],
          ),
        ));
  }
}

class MyGoods extends StatefulWidget {
  //Tab界面的所有商品列表类
  MyGoods({Key key, this.data}) : super(key: key);
  final List data;
  _MyGoodsState _myGoodsState;

  @override
  _MyGoodsState createState() {
    _myGoodsState = new _MyGoodsState(data);
    return _myGoodsState;
  }

  void fresh() {
    _myGoodsState.fresh();
  }
}

class _MyGoodsState extends State<MyGoods> {
  int nums = 0;
  List<Widget> t = [];
  List data;
  bool isLoading = false;

  _MyGoodsState(this.data);

  void fresh() {
    //刷新数据
    data = mylist;
    print('看看data.........');
    print(data[0]);
    print("看看字符.....");
    print(data[0]["imageUrl"]);
    print(data[0]["imageUrl"] is String);
    getData();
  }

  getData() {
    //获取数据函数
    t = [];
    setState(() {
      for (int i = 0; i < 10; i++) {
        if (i >= data.length) break;
        t.add(Agood(data[i]["information"], data[i]["imageUrl"],
            data[i]["score"], data[i]["number"]));
      }
    });
    print('加载新数据............');
  }

  @override
  void initState() {
    //初始化函数、带监听滑动功能
    super.initState();
    getData();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        print("已经滑到最底部");
        _getMore();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    //列表显示函数
    return Container(
      child: ListView.builder(
          controller: scrollController,
          itemCount: 1,
          itemBuilder: (BuildContext context, int index) {
            return SingleChildScrollView(
              child: Column(
                children: t,
              ),
            );
          }),
    );
  }

  Future _getMore() async {
    //加载更多函数
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      await Future.delayed(Duration(seconds: 2), () {
        print("加载更多");
        setState(() {
          nums += 10;
          for (int i = nums - 10; i < nums; i++) {
            if (i >= data.length) break;
            t.add(Agood(data[i]["infomation"], data[i]["imageUrl"],
                data[i]["score"], data[i]["number"]));
          }
          isLoading = false;
        });
      });
    }
  }
}

//搜索栏部件
class SearchBarWidget extends StatelessWidget {
  TextEditingController _searchedit;
  @override
  Widget build(BuildContext context) {
    return Container(
        alignment: Alignment.center, //容器居中
        child: Column(children: [
          SizedBox(
            height: 75.0,
          ),
          SizedBox(
            child: Container(
              width: 300.0, //控制容器的宽度
              height: 30.0,
              padding: EdgeInsets.fromLTRB(40, 2, 8, 2), //控制内边距
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(50), //将容器设为圆角
                color: Colors.grey[300], //容器颜色为透明
              ),
              alignment: Alignment.center,
              child: TextField(
                controller: _searchedit,
                //文本域定义，最大显示一行
                maxLines: 1,
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(
                      vertical: -11.0, horizontal: 0.0),
                  // 设置搜索图片
                  prefixIcon: Padding(
                      padding: EdgeInsets.fromLTRB(80, 0, 0, 0),
                      child: Icon(
                        Icons.search,
                        size: 20,
                      )),
                  prefixIconConstraints: BoxConstraints(
                    //设置搜索图片左对齐
                    minWidth: 30,
                    minHeight: 25,
                  ),
                  //控制提示信息
                  hintText: '搜索',
                  hintStyle: TextStyle(color: Colors.grey),
                  border: InputBorder.none,
                ),
                style: TextStyle(color: Colors.black),
              ),
            ),
          ),
        ]));
  }
}
